package com.gec.zhs.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.util.Date;

/**
 * @author zhs
 * @version 1.0
 * @date 2025-08-25
 * @description langchain4j传递的日期参数"createTime" : {
 *     "cdate" : {
 *       "cachedFixedDateJan1" : 20250101,
 *       "cachedFixedDateNextJan1" : 20260101,
 *       "cachedYear" : 2025
 *     },
 *     "fastTime" : 1734883200000
 *   },与json的格式不符合，会出现日期转换异常
 *   自定义处理
 */
public class LangChainDateDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        JsonNode node = jp.getCodec().readTree(jp);

        // 尝试从 fastTime 字段获取时间戳
        if (node.isObject()) {
            if (node.has("fastTime")) {
                long timestamp = node.get("fastTime").asLong();
                return new Date(timestamp);
            }
            // 处理更深层次的嵌套结构
            else if (node.has("cdate") || node.has("date")) {
                for (JsonNode childNode : node) {
                    if (childNode.isObject() && childNode.has("fastTime")) {
                        long timestamp = childNode.get("fastTime").asLong();
                        return new Date(timestamp);
                    }
                }
            }
        }
        else if (node.isNumber()) {
            return new Date(node.asLong());
        }
        else if (node.isTextual()) {
            try {
                // 尝试解析为标准日期格式
                return ctxt.parseDate(node.asText());
            } catch (Exception e) {
                throw new IOException("无法解析日期: " + node.asText(), e);
            }
        }

        String nodeStr = node.toString();
        throw new IOException("无法解析日期对象: " + (nodeStr.length() > 100 ? nodeStr.substring(0, 100) + "..." : nodeStr));
    }
}